<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/5 0005
 * Time: 13:19
 */

namespace app\common;

use think\Exception;

class VodAliyun
{

    protected $data;
    protected $accessKeyId = 'LTAI4G2uj3BHRSryiy241PRJ';
    protected $accessKeySecret = 'ap58wwMCa5aUZVfo0wy7ooIh13qbmQ';
    protected $apiRegionId = 'cn-shanghai';
    protected $url = 'http://vod.cn-shanghai.aliyuncs.com/?';

    function __construct($action)
    {
        $this->data = array(
            // 公共参数
            'Format' => 'json',
            'Version' => '2017-03-21',
            'AccessKeyId' => $this->accessKeyId,
            'SignatureVersion' => '1.0',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => md5(uniqid(mt_rand(), true)),
            'TimeStamp' => gmdate('Y-m-d\TH:i:s\Z'),
        );
        $this->data = array_merge($this->data, $action);
    }

    // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
    public function percentEncode($str)
    {
        $res = urlencode($str);
        $res = str_replace(array('+', '*'), array('%20', '%2A'), $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    public function computeSignature($parameters, $accessKeySecret)
    {

        // 将参数Key按字典顺序排序
        ksort($parameters);
        
        // 生成规范化请求字符串
        $canonicalizedQueryString = '';
        foreach ($parameters as $key => $value) {
            $canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
        }
        
        // 生成用于计算签名的字符串 stringToSign
        $stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));

        // 计算签名，注意accessKeySecret后面要加上字符'&'
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));

        
        return $signature;
    }

    public function callInterface()
    {
        // 计算签名并把签名结果加入请求参数
        $this->data['Signature'] = $this->computeSignature($this->data, $this->accessKeySecret);
        // 发送请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url . http_build_query($this->data));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        $res = json_decode($res);
        return $res;
    }

    /**
     * @param $action
     * @param $videoId
     * http://vod.cn-shanghai.aliyuncs.com/?Action=GetVideoInfo&VideoId=93ab850b4f6f44eab54b6e91d24d81d4&Format=JSON&<公共参数>
     */
    public function getVideoInfo($action)
    {
        
        $vod = new VodAliyun($action);
        $result = $vod->callInterface();
        return $result;
    }

    /***
     *     http://vod.cn-shanghai.aliyuncs.com/?Action=GetPlayInfo&VideoId=93ab850b4f*****b54b6e91d24d81d4&Format=JSON&<公共参数>
     * 返回播放地址
     */
    public function getPlayInfo($action)
    {

    }
}